package com.xky.ui.module.supplierManagement.add;

import com.xky.utils.DBUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;

public class AddSuppliers extends JFrame {
    private JPanel mainPanel;
    private JTextField[] textFields;
    private JComboBox<String> isActiveComboBox;
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    
    // 邮箱验证正则表达式
    private static final String EMAIL_REGEX = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
    
    public AddSuppliers() {
        setTitle("添加供应商");
        setSize(550, 650);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        init();
        setVisible(true);
    }

    void init() {
        // 创建主面板并设置背景渐变
        JPanel backgroundPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                int w = getWidth();
                int h = getHeight();
                GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, w, h);
            }
        };
        backgroundPanel.setLayout(new BorderLayout(10, 10));
        backgroundPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        
        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setOpaque(false);
        
        JLabel titleLabel = new JLabel("添加供应商信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setForeground(PRIMARY_COLOR);
        titlePanel.add(titleLabel);
        
        // 添加分隔线
        JSeparator separator = new JSeparator();
        separator.setForeground(PRIMARY_COLOR);
        separator.setPreferredSize(new Dimension(450, 2));
        
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);
        headerPanel.add(titlePanel, BorderLayout.CENTER);
        headerPanel.add(separator, BorderLayout.SOUTH);
        headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
        
        backgroundPanel.add(headerPanel, BorderLayout.NORTH);
        
        // 表单面板
        JPanel formCard = createRoundedPanel();
        formCard.setLayout(new BorderLayout());
        
        mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setOpaque(false);
        
        GridBagConstraints gbc = new GridBagConstraints();
        
        JLabel[] labels = new JLabel[]{
                new JLabel("供应商编码 *"),
                new JLabel("供应商名称 *"),
                new JLabel("联系人姓名 *"),
                new JLabel("联系人电话 *"),
                new JLabel("联系人邮箱 *"),
                new JLabel("供应商地址 *"),
                new JLabel("是否合作 *")
        };
        
        // 创建文本框
        textFields = new JTextField[6]; // 只需要6个文本框，另一个是下拉框
        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
        Font inputFont = new Font("微软雅黑", Font.PLAIN, 16);

        for (int i = 0; i < labels.length; i++) {
            gbc.gridx = 0;
            gbc.gridy = i;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.insets = new Insets(10, 20, 10, 10);
            labels[i].setFont(labelFont);
            labels[i].setForeground(PRIMARY_COLOR);
            mainPanel.add(labels[i], gbc);
            
            gbc.gridx = 1;
            gbc.weightx = 1.0;
            
            if (i < 6) {
                textFields[i] = new JTextField(20);
                textFields[i].setFont(inputFont);
                textFields[i].setPreferredSize(new Dimension(300, 35));
                gbc.fill = GridBagConstraints.HORIZONTAL;
                mainPanel.add(textFields[i], gbc);
            } else {
                isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
                isActiveComboBox.setFont(inputFont);
                isActiveComboBox.setPreferredSize(new Dimension(300, 35));
                isActiveComboBox.setBackground(Color.WHITE);
                gbc.fill = GridBagConstraints.HORIZONTAL;
                mainPanel.add(isActiveComboBox, gbc);
            }
        }
        
        // 添加字段说明标签
        JLabel noteLabel = new JLabel("<html><body style='width: 350px'>" +
                "<p style='color: #666666;'>注意：带 * 的字段为必填项</p>" +
                "</body></html>");
        noteLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
        gbc.gridx = 0;
        gbc.gridy = labels.length;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(20, 20, 10, 10);
        mainPanel.add(noteLabel, gbc);
        
        formCard.add(mainPanel, BorderLayout.CENTER);
        formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        backgroundPanel.add(formCard, BorderLayout.CENTER);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setOpaque(false);
        
        JButton submitButton = new JButton("提交");
        submitButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        submitButton.setPreferredSize(new Dimension(120, 40));
        submitButton.setBackground(BUTTON_COLOR);
        submitButton.setForeground(Color.WHITE);
        submitButton.setFocusPainted(false);
        submitButton.setBorderPainted(false);
        
        JButton cancelButton = new JButton("取消");
        cancelButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        cancelButton.setPreferredSize(new Dimension(120, 40));
        cancelButton.setBackground(Color.LIGHT_GRAY);
        cancelButton.setForeground(Color.WHITE);
        cancelButton.setFocusPainted(false);
        cancelButton.setBorderPainted(false);
        
        buttonPanel.add(submitButton);
        buttonPanel.add(cancelButton);
        
        backgroundPanel.add(buttonPanel, BorderLayout.SOUTH);
        add(backgroundPanel);
        
        // 提交按钮事件
        submitButton.addActionListener(_ -> {
            String supplierCode = textFields[0].getText().trim();
            String supplierName = textFields[1].getText().trim();
            String contactName = textFields[2].getText().trim();
            String contactPhone = textFields[3].getText().trim();
            String contactEmail = textFields[4].getText().trim();
            String address = textFields[5].getText().trim();
            String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1，"否"对应0
            
            // 验证所有字段是否已填写
            if (supplierCode.isEmpty() || supplierName.isEmpty() || contactName.isEmpty() || 
                contactPhone.isEmpty() || contactEmail.isEmpty() || address.isEmpty()) {
                JOptionPane.showMessageDialog(AddSuppliers.this, "所有字段都为必填项，请完成表单", "输入提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            // 验证邮箱格式
            if (!contactEmail.matches(EMAIL_REGEX)) {
                JOptionPane.showMessageDialog(AddSuppliers.this, "邮箱格式错误，请重新输入", "错误提示", JOptionPane.ERROR_MESSAGE);
                textFields[4].setText("");
                textFields[4].requestFocus();
                return;
            }
            
            // 验证邮箱是否重复
            if (selectByEmail(contactEmail)) {
                JOptionPane.showMessageDialog(AddSuppliers.this, "邮箱号重复，请更换", "重复提示", JOptionPane.ERROR_MESSAGE);
                textFields[4].setText("");
                textFields[4].requestFocus();
                return;
            }
            
            // 确认添加
            if (JOptionPane.showConfirmDialog(AddSuppliers.this, "你确定要添加该信息吗？", "添加提示", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.YES_OPTION) {
                addSupplier(supplierCode, supplierName, contactName, contactPhone, contactEmail, address, isActive);
                JOptionPane.showMessageDialog(AddSuppliers.this, "信息添加成功", "成功提示", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            }
        });

        // 取消按钮事件
        cancelButton.addActionListener(_ -> dispose());
    }
    
    /**
     * 创建带圆角和阴影的面板
     */
    private JPanel createRoundedPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(Color.WHITE);
                g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
            }
        };
        panel.setOpaque(false);
        
        // 添加阴影边框
        panel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5),
            BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)
            )
        ));
        
        return panel;
    }

    // 添加信息到数据库
    public void addSupplier(String supplierCode, String supplierName, String contactName, String contactPhone, String contactEmail, String address, String isActive) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement(
                "INSERT INTO suppliers(supplier_code, supplier_name, contact_name, contact_phone, contact_email, address, is_active, created_time, updated_time) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())",
                Statement.RETURN_GENERATED_KEYS
            );
            preparedStatement.setString(1, supplierCode);
            preparedStatement.setString(2, supplierName);
            preparedStatement.setString(3, contactName);
            preparedStatement.setString(4, contactPhone);
            preparedStatement.setString(5, contactEmail);
            preparedStatement.setString(6, address);
            preparedStatement.setString(7, isActive);
            
            int i = preparedStatement.executeUpdate();
            if (i > 0) {
                System.out.println("受影响的行数为" + i + "添加成功！");
            } else {
                System.out.println("受影响的行数为" + i + "添加失败！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }

    // 查询邮箱是否重复
    public boolean selectByEmail(String email) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("SELECT * FROM suppliers WHERE contact_email = ?");
            preparedStatement.setString(1, email);
            resultSet = preparedStatement.executeQuery();
            return resultSet.next();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.closeAll(connection, preparedStatement, resultSet);
        }
    }

    public static void main(String[] args) {
        try {
            // 尝试使用系统外观
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        SwingUtilities.invokeLater(AddSuppliers::new);
    }
}
